﻿using CommonFunction;
using MyWPF.Models.Recipe;
using MyWPF.Models.UserManagement;
using MyWPF.StaticData;
using MyWPF.Views.Others;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using WPFDevelopers.Controls;

namespace MyWPF.Models.Load
{
    public class LoadHelper : ILoad
    {
        public LoadHelper()
        {
            //配置加载初始化
            ConfigLoad();
            //查询是否存在多开现象
            BanMore();
            //初始化全局按键事件
            KeyBoardHook();
            //初始化用户管理
            LoadUser();
            //初始化配方数据库
            LoadRecipe();
        }

        /// <summary>
        /// 加载基础设置，并且如果是开发者电脑，版本号就自增
        /// </summary>
        public void ConfigLoad()
        {
            string path = @"Assets\Json\Config.json";
            // 读取 JSON 文件
            using (StreamReader sr = new StreamReader(path))
            {
                string json = sr.ReadToEnd();
                StaticModels.staticInfo.config = JsonConvert.DeserializeObject<StaticData.Config>(json);
            }

            //初始化语言
            StaticModels.vM_SetWindow_Normal.LanguageSelected = StaticModels.staticInfo.config.NomalConfig.Language;

            //初始化各种按钮
            StaticModels.vM_SetWindow_Normal.AutoStart = StaticModels.staticInfo.config.NomalConfig.AutoStart;
            StaticModels.vM_SetWindow_Normal.BanMore = StaticModels.staticInfo.config.NomalConfig.BanMore;

            //如果是开发者电脑就把版本号+1
            //版本号自增
            PCHelper pCHelper = new PCHelper();
            string sn = pCHelper.GetMBSN();
            int NewNo = Convert.ToInt16(StaticModels.staticInfo.config.VersionConfig.Version.Substring(StaticModels.staticInfo.config.VersionConfig.Version.Length - 3, 3));
            //如果是开发电脑，版本号就增加
            if (sn == "L1HF07S00JG")
                NewNo++;
            string NewNo_Str = NewNo.ToString();
            //不够3位数就补充0
            for (int i = 0; i < 3; i++)
            {
                if (NewNo_Str.Length > 2)
                    break;
                else
                    NewNo_Str = "0" + NewNo_Str;
            }
            StaticModels.staticInfo.config.VersionConfig.Version = StaticModels.staticInfo.config.VersionConfig.Version.Substring(0, StaticModels.staticInfo.config.VersionConfig.Version.Length - 3) + NewNo_Str;

            //将StaticModels.staticInfo.config序列化后保存
            string configStr = JsonConvert.SerializeObject(StaticModels.staticInfo.config);
            var filePath = path;
            File.WriteAllText(filePath, configStr);
        }

        /// <summary>
        /// 禁止多开
        /// </summary>
        public void BanMore()
        {
            if (StaticModels.staticInfo.config.NomalConfig.BanMore)
            {
                Process currentProcess = Process.GetCurrentProcess();
                Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
                foreach (Process process in processes)
                {
                    if (process.Id != currentProcess.Id)
                    {
                        if (Assembly.GetExecutingAssembly().Location.Replace(@"/", @"\") == currentProcess.MainModule.FileName)
                        {
                            Tips tips = new Tips("请勿多开！");
                            tips.ShowDialog();
                            System.Environment.Exit(0);

                        }
                    }
                }
            }

        }

        /// <summary>
        /// 全局按键
        /// </summary>
        public void KeyBoardHook()
        {
            keyboardHookHelper.KeyDownEvent += new KeyEventHandler(hook_KeyDown);//钩住键按下
            keyboardHookHelper.Start();//安装键盘钩子
        }
        KeyboardHookHelper keyboardHookHelper = new KeyboardHookHelper();
        private void hook_KeyDown(object sender, KeyEventArgs e)
        {
            //判断按下的键（Alt + F1）
            if (e.KeyValue == (int)Keys.F1 && (int)Control.ModifierKeys == (int)Keys.Alt)
            {
                var screenCut = new ScreenCut();
                screenCut.ShowDialog();
            }
        }

        /// <summary>
        /// 初始化用户管理数据库
        /// </summary>
        public void LoadUser()
        {
            //初始化用户数据库
            UserDbContext UserDb = new UserDbContext()
            {
                Path = @"Assets\LiteDB",
                DbName = "User.db",
                Password = "cheems"
            };
            StaticModels.user.LoadDB(UserDb);
        }

        /// <summary>
        /// 初始化配方数据库
        /// </summary>
        public void LoadRecipe()
        {
            //初始化配方数据库
            RecipeDbContext RecipeDb = new RecipeDbContext()
            {
                Path = @"Assets/LiteDB",
                DbName = "Recipe.db",
                Password = "cheems",
            };
            StaticModels.recipe.LoadDB(RecipeDb);

        }
    }


}
